## #!/usr/bin/python3
# coding=utf-8
import os
import sys
import struct
import socket
import configparser
import time

# 对于服务器，要求接受下列形式的报文
#struct notify_message {
#    int token;
#    char tittle[128];
#    char message[128];
#    int  duration;
#    char type[128];
#    char url[128];
#};

def remove_quot(string):
    tmp =  string.replace('\"', '')
    return tmp.replace('\'', '')

def fill_to(bytes_obj, lenth):
    tmp_bytes = bytearray(bytes_obj)
    ret_bytes = bytearray(bytes(lenth))
    #print(ret_bytes.__len__())

    if(len(bytes_obj) >= lenth):
        return tmp_bytes[:lenth]
    else :
        i = 0
        while(i < lenth):
            if(i < tmp_bytes.__len__()):
                ret_bytes[i] = tmp_bytes[i]
            else :
                break
            i = i+1
    return ret_bytes

def let_me_know(cf, case):
     
    server_ip=cf.get(case,"host")
    server_port=cf.getint(case,"port")
    try :
        token=cf.getint(case,"token")
    except Exception as e:
        token = 0

    try :
        tittle=cf.get(case,"tittle")
    except Exception as e:
        tittle = "Let me know"
    tittle =  remove_quot(tittle)
    
    try :
        msg=str(cf.get(case,"msg"))
    except Exception as e:
        msg = ""
    msg =  remove_quot(msg)
     
    try :
        mtype=cf.get(case,"type")
    except Exception as e:
        mtype = "info"
    
    try :
        duration=cf.getint(case,"duration")
    except Exception as e:
        duration = 10
    try :
        url=cf.getint(case,"url")
    except Exception as e:
        url = ""

    tmp = struct.pack('i',token)
    buff_send = tmp
    ## 构造，准备发送
    tmp = tittle.encode();
    tmp = fill_to(tmp, 128)
    buff_send = buff_send + tmp

    tmp = msg.encode();
    tmp = fill_to(tmp, 128)
    buff_send = buff_send + tmp

    tmp = struct.pack('i',duration)
    buff_send = buff_send + tmp

    tmp = mtype.encode();
    tmp = fill_to(tmp, 128)
    buff_send = buff_send + tmp

    tmp = url.encode();
    tmp = fill_to(tmp, 128)
    buff_send = buff_send + tmp

    tcp_client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server_addr = (server_ip, server_port)
    tcp_client_socket.connect(server_addr)
    tcp_client_socket.sendall(buff_send)

## 获取当前脚本所在位置，以获取 对应的 配置文件
INIT_FILE=".client.ini"
BASE_DIR = os.path.dirname(os.path.abspath(sys.argv[0]))
CONFIG_INI=BASE_DIR+"/"+ INIT_FILE
#print("abs path is %s" %(BASE_DIR))
#print("Config %s" %(CONFIG_INI))
cf = configparser.ConfigParser()
cf.read(CONFIG_INI)
# 判断 参数，用于 批量处理通知
argc = len(sys.argv)
if argc > 1 :
    for i in sys.argv[1:]:
        #print(i)
        let_me_know(cf, i)
        time.sleep(1)
else :
    let_me_know(cf, "default")
 
